import { TokenService } from './token.service';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, of, throwError } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class AuthService {
  redirectUrl: string;

  constructor(private token: TokenService) { }

  isAuthenticated(): Observable<boolean> {
    return this.token.get().pipe(
      map(token => !!token)
    );
  }

  authenticate(account: string, password: string): Observable<boolean> {
    if ('admin' === account && 'password' === password) {
      return this.token.set(account + ' is authenticated!').pipe(
        map(() => true)
      );
    } else {
      return throwError('账户密码错误，请重新验证！');
    }
  }

  logout(): Observable<boolean> {
    this.token.clear();
    return of(true);
  }
}
